#!/bin/bash

# toggle hdmi to enable frame buffer device

drm_base=/sys/class/drm
hdmi_status=$drm_base/card0-HDMI-A-1/status

sysfb="/sys/class/graphics"
mainfb=fb0
i=0
while [ $i -ne 5 ]
do
    if [ -f ${sysfb}/fb${i}/name ]; then
        if grep fb_ssd1306 ${sysfb}/fb${i}/name 2>&1 >/dev/null; then
            echo ""
        else
            mainfb="fb${i}"
            break
        fi
    else
        break
    fi
    i=$(($i+1))
done

if ! grep "^connected" $drm_base/card0-*/status >/dev/null; then
    if [ -f $hdmi_status ]; then
        echo on > $hdmi_status

        for n in $(seq 10); do
            [ -c /dev/${mainfb} ] && break
            sleep 1
        done

        if [ -d usr/share/xsessions ]; then
            # x11
            for n in $(seq 30); do
                [ -e /tmp/.X11-unix/X0 ] && break
                sleep 1
            done
        else
            sleep 20 
        fi

        sleep 2
        echo detect > $hdmi_status
    fi
fi

echo "DRM setup:  Completed" > /dev/kmsg
